package org.nimi317.web_gis.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nimi317.web_gis.form.post.IdwPost;
import org.nimi317.web_gis.dao.IdwDao;
import org.nimi317.web_gis.entity.Idw;
import org.nimi317.web_gis.service.IdwService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * idw表(Idw)表服务实现类
 *
 * @author makejava
 * @since 2024-05-10 14:04:39
 */
@Service("idwService")
public class IdwServiceImpl extends ServiceImpl<IdwDao, Idw> implements IdwService {

    private final IdwService service;

    public IdwServiceImpl(@Lazy IdwService service) {
        this.service = service;
    }

    @Override
    public Integer isExist(IdwPost map) {
        Integer id = service.isExistAndGetId(map);
        if (ObjectUtil.isNotNull(id)) {
            return id;
        }
        Idw idw = new Idw();
        BeanUtils.copyProperties(map, idw);
        this.save(idw);
        return idw.getId();
    }

    @Override
    public Integer isExistAndGetId(IdwPost map) {
        LambdaQueryWrapper<Idw> wrapper = getWrapper(map, Idw::getId, Idw::getPower, Idw::getWidth, Idw::getDistance, Idw::getField, Idw::getRange);
        Idw one = this.getOne(wrapper);
        if (ObjectUtil.isEmpty(one)) {
            return null;
        }
        return one.getId();
    }

    @SafeVarargs
    private LambdaQueryWrapper<Idw> getWrapper(IdwPost post, SFunction<Idw, ?> select, SFunction<Idw, ?>... fun) {
        Idw idw = new Idw();
        BeanUtils.copyProperties(post, idw);
        LambdaQueryWrapper<Idw> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(select);
        for (SFunction<Idw, ?> f : fun) {
            wrapper.eq(f, f.apply(idw));
        }
        return wrapper;
    }
}

